import { useEffect, useState } from 'react';
import {
	Button,
	Form,
	Input,
	Selector,
	DatePicker,
	Switch,
	CheckList,
	Radio,
	TextArea,
	Dialog,
	Toast,
} from 'antd-mobile';
import rrwebPlayer from 'rrweb-player';
import 'rrweb-player/dist/style.css';
import { monitorSdk } from '../../../../lib/index.esm';

const BehaviorRecorder = () => {
	const [isTranscribe, setIsTranscribe] = useState(false);
	const [dialogVisible, setDialogVisible] = useState(false);
	const [events, setEvents] = useState([]);

	// Recording functions
	const transcribe = () => {
		setIsTranscribe(true);
		monitorSdk.behaviorRecorder.start();
	};

	const pause = () => {
		setIsTranscribe(false);
		const recordedEvents = monitorSdk.behaviorRecorder.stop();
		setEvents(recordedEvents);
	};

	const play = () => {
		setDialogVisible(true);
		pause();
	};

	useEffect(() => {
		if (dialogVisible && events.length > 0) {
			setTimeout(() => {
				let replayer = new rrwebPlayer({
					// eslint-disable-next-line no-undef
					target: document.getElementById('playback'),
					// 配置项
					props: {
						events,
					},
				});
				replayer.addEventListener('finish', () => {
					console.log('finish');
				});
			}, 0);
		}
	}, [dialogVisible, events]);

	// ============================================================
	const [form] = Form.useForm();

	// Form options
	const regionOptions = [
		{ label: 'Zone one', value: 'shanghai' },
		{ label: 'Zone two', value: 'beijing' },
	];

	const countOptions = Array.from({ length: 10 }).map((_, idx) => ({
		label: `${idx + 1}`,
		value: `${idx + 1}`,
	}));

	const activityTypeOptions = [
		{ label: 'Online activities', value: 'online' },
		{ label: 'Promotion activities', value: 'promotion' },
		{ label: 'Offline activities', value: 'offline' },
		{ label: 'Simple brand exposure', value: 'exposure' },
	];

	const resourceOptions = [
		{ label: 'Sponsorship', value: 'sponsorship' },
		{ label: 'Venue', value: 'venue' },
	];

	// Form handlers
	const submitForm = async () => {
		try {
			const values = await form.validateFields();
			console.log('Submit success:', values);
			Toast.show({ content: 'Submit success' });
		} catch (error) {
			console.log('Submit failed:', error);
			Toast.show({ content: 'Please fill all required fields' });
		}
	};

	const resetForm = () => {
		form.resetFields();
	};

	return (
		<div style={{ padding: 16 }}>
			{/* Recording alert */}
			{isTranscribe && (
				<div
					style={{
						background: '#fff2f0',
						color: '#d4380d',
						padding: '8px 12px',
						marginBottom: 16,
						borderRadius: 4,
					}}
				>
					屏幕录制中...
				</div>
			)}

			{/* Recording controls */}
			<div style={{ marginTop: 40, display: 'flex', gap: 8 }}>
				<Button color='primary' onClick={transcribe}>
					录制
				</Button>
				<Button color='warning' onClick={pause}>
					暂停
				</Button>
				<Button color='success' onClick={play}>
					播放
				</Button>
			</div>

			{/* Playback dialog */}
			<Dialog
				style={{ width: '1960px', height: '760px' }}
				visible={dialogVisible}
				onClose={() => setDialogVisible(false)}
				content={<div id='playback' />}
			/>

			{/* Form */}
			<div style={{ maxWidth: 400, margin: '40px auto' }}>
				<Form
					form={form}
					initialValues={{
						name: 'Hello',
						delivery: false,
					}}
					footer={
						<div style={{ display: 'flex', gap: 8 }}>
							<Button block color='primary' onClick={submitForm}>
								Create
							</Button>
							<Button block onClick={resetForm}>
								Reset
							</Button>
						</div>
					}
				>
					<Form.Item
						name='name'
						label='Activity name'
						rules={[
							{ required: true, message: 'Please input Activity name' },
							{ min: 3, max: 5, message: 'Length should be 3 to 5' },
						]}
					>
						<Input placeholder='Please input' />
					</Form.Item>

					<Form.Item
						name='region'
						label='Activity zone'
						rules={[{ required: true, message: 'Please select Activity zone' }]}
					>
						<Selector options={regionOptions} placeholder='Activity zone' />
					</Form.Item>

					<Form.Item
						name='count'
						label='Activity count'
						rules={[
							{ required: true, message: 'Please select Activity count' },
						]}
					>
						<Selector options={countOptions} placeholder='Activity count' />
					</Form.Item>

					<Form.Item
						name='date1'
						label='Activity date'
						rules={[{ required: true, message: 'Please pick a date' }]}
					>
						<DatePicker></DatePicker>
					</Form.Item>

					<Form.Item
						name='date2'
						label='Activity time'
						rules={[{ required: true, message: 'Please pick a time' }]}
					>
						<DatePicker mode='time'></DatePicker>
					</Form.Item>

					<Form.Item
						name='delivery'
						label='Instant delivery'
						valuePropName='checked'
					>
						<Switch />
					</Form.Item>

					<Form.Item
						name='type'
						label='Activity type'
						rules={[{ required: true, message: 'Please select at least one' }]}
					>
						<CheckList multiple>
							{activityTypeOptions.map(option => (
								<CheckList.Item key={option.value} value={option.value}>
									{option.label}
								</CheckList.Item>
							))}
						</CheckList>
					</Form.Item>

					<Form.Item
						name='resource'
						label='Resources'
						rules={[
							{ required: true, message: 'Please select activity resource' },
						]}
					>
						<Radio.Group>
							{resourceOptions.map(option => (
								<Radio key={option.value} value={option.value}>
									{option.label}
								</Radio>
							))}
						</Radio.Group>
					</Form.Item>

					<Form.Item
						name='desc'
						label='Activity form'
						rules={[{ required: true, message: 'Please input activity form' }]}
					>
						<TextArea placeholder='Please input' rows={3} />
					</Form.Item>
				</Form>
			</div>
		</div>
	);
};

export default BehaviorRecorder;
